<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.cpbh" placeholder="车票编号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button> -->
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
      <br>
      <el-col :span="6">
        线路名称：<el-input disabled style="width: 200px;" :value="sfcz"/> 
      </el-col>
      <el-col :span="6">
        发车时间：<el-input disabled style="width: 200px;" :value="rqsj"/> 
      </el-col>
      <el-col :span="6">
        检票状态：<el-input disabled style="width: 200px;" :value="sfjp"/> 
      </el-col>
      <el-col :span="6">
        目的站名：<el-input disabled style="width: 200px;" :value="mdcz" v-model="mdcz"/> 
      </el-col>
      <el-col :span="6">
        车票类型：<el-input disabled style="width: 200px;" :value="cplx"/> 
      </el-col>
      <el-col :span="6">
        售票时间：<el-input disabled style="width: 200px;" :value="spsj"/> 
      </el-col>
      <el-col :span="6">
        车票价格：<el-input disabled style="width: 200px;" :value="pj"/> 
      </el-col>
      <el-col :span="6">
        车票状态：<el-input disabled style="width: 200px;" :value="cpzt"/> 
      </el-col>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="目的站名" prop="mdcz" align="center" width="80">
      </el-table-column>
      <el-table-column label="座位数" align="center" prop='zwh'>
      </el-table-column>
      <el-table-column label="发车时间" align="center" prop='fcsj'>
      </el-table-column>
      <el-table-column label="班次号" align="center" prop='bcbh'>  
      </el-table-column>
      <el-table-column label="线路名称" class-name="status-col" align="center" prop='xlmc'>    
      </el-table-column>
      <el-table-column label="检票口" class-name="status-col" align="center" prop='jpk'>    
      </el-table-column>
      <el-table-column label="票价" class-name="status-col" align="center" prop='pj'>   
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            改乘
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:10px;">
        <el-form-item label="发车时间" prop="yhbh">
          <el-input v-if="dialogStatus != 'create'" v-model="temp.yhbh" />
          <el-input v-else v-model="temp.yhbh" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { show_cpb_by_bbkh, show_by_mdcz_list} from '@/api/fuwu'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable22',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        order_by:'cpbh_asc',
        cpbh:''
        // cpbh:100
      },
      sfcz:'',
      mdcz:'',
      pj:'',
      rqsj:'',
      cplx:'',
      cpzt:'',
      sfjp:'',
      spsj:'',
      zwh:'',
      jpfs:'',
      jpk:'',
      xlbh:'',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+cpbh' }, { label: 'ID Descending', key: '-cpbh' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      czqx_list:['总控','报班','售票','服务台','检票','财务','查询']
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      show_cpb_by_bbkh(this.listQuery).then(response => {
        console.log("response.data.items",response)
        this.sfcz=response.data.items[0].sfcz
        this.mdcz=response.data.items[0].mdcz
        this.pj=response.data.items[0].pj
        this.rqsj=response.data.items[0].rqsj
        this.cplx=response.data.items[0].cplx
        this.cpzt=response.data.items[0].cpzt
        this.sfjp=response.data.items[0].sfjp
        this.spsj=response.data.items[0].spsj
        this.zwh=response.data.items[0].zwh
        this.jpfs=response.data.items[0].jpfs
        this.jpk=response.data.items[0].jpk
        this.xlbh=response.data.items[0].xlbh
        // this.list = response.data.items
        // this.total = response.data.total
        this.listLoading = false
        this.select_by_mdcz_list(this.xlbh)
      })   
    },
    // 根据目的站进行搜索改乘线路
    select_by_mdcz_list(xlbh) {
      show_by_mdcz_list(xlbh).then(response => {
        console.log("response___",response)
        this.list =response.data.items
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {//排序发生变化事件
      const { prop, order } = data
      if (prop === 'cpbh') {
        this.sortByCPBH(order)
      }
    },
    sortByCPBH(order) {//按用户编号排序
      let cur = this.listQuery.order_by.split('_')
      if (order === 'ascending') {
        this.listQuery.order_by = cur[0]+'_'+'asc'
      } else {
        this.listQuery.order_by = cur[0]+'_'+'desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      console.log()
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['目的站名', '座位数', '发车时间', '班次号', '线路名称', '检票口', '票价']
        const filterVal = [
          'yhbh', 
          '22', 
          '2021/10/18 22:54', 
          'yhgs', 
          'yhzt', 
          'yhzt', 
          'yhzt'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
}
</script>